package com.matriq.cloudmanager;

import java.io.File;

import com.matriq.cloudmanager.R;
import com.matriq.cloudmanager.dialog.DownloadDialog;
import com.matriq.cloudmanager.dialog.UpdateNoticeDialog;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import net.lgpage.activity.BaseActivity;
import net.lgpage.dialog.DialogListener;
import net.lgpage.http.ExceptionAsyncTask;
import net.lgpage.http.HttpConnectionUtil;
import net.lgpage.service.VersionApk;
import net.lgpage.tool.GsonTool;
import net.lgpage.util.Cleaner;
import net.lgpage.util.IntentUtil;

public class VersionActivity extends BaseActivity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_version);

		setViews();
		setEvents();
		loadData();
	}

	LinearLayout ll[] = new LinearLayout[3];
	ImageView iv_logo;
	ScrollView sv;
	TextView tv_title;
	ImageButton ll_back;
	TextView tv_check_result;
	TextView tv_version;

	private void setViews() {
		ll[0] = (LinearLayout) this.findViewById(R.id.ll0);
		ll[1] = (LinearLayout) this.findViewById(R.id.ll1);
		ll[2] = (LinearLayout) this.findViewById(R.id.ll2);
		iv_logo = (ImageView) this.findViewById(R.id.iv_logo);
		sv = (ScrollView) this.findViewById(R.id.sv);
		tv_title = (TextView) this.findViewById(R.id.tv_title);
		ll_back = (ImageButton) this.findViewById(R.id.ll_back);
		tv_check_result = (TextView) this.findViewById(R.id.tv_check_result);
		tv_version = (TextView) this.findViewById(R.id.tv_version);
	}

	private void setEvents() {
		ll[1].setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				reloadObj();
			}
		});
		ll[2].setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startActivity(IntentUtil.toCall("15198252317"));
			}
		});
	}

	Object obj;

	public void setData(Object obj) {
		this.obj = obj;
		tv_title.setText(null);
		tv_check_result.setText(null);
		tv_version.setText(null);
	}

	private void loadData() {
		try {
			String versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
			tv_version.setText(versionName);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		reloadObj();
	}
	UpdateTask task;
	public void reloadObj(){
		if(task != null){
			task.cancel(true);
		}
		task = new UpdateTask(this);
		task.execute();
	}
	
	public VersionApk getVersionInfo(String packagename,String versiontype) throws Exception {
		String res = HttpConnectionUtil.requestUrl("http://api.fir.im/apps/latest/56e5063d00fc740a79000016?api_token=58aeedba1a88313b78807e7a8bed2044", "GET", null, "application/x-www-form-urlencoded");
		VersionApk va =GsonTool.getGson().fromJson(res, VersionApk.class);
		return va;
	}
	
	class UpdateTask extends ExceptionAsyncTask<VersionApk>{

		public UpdateTask(Context context) {
			super(context);
		}
		
		@Override
		public VersionApk doInBackgroundX(String... params) throws Exception {
			return getVersionInfo(getPackageName(),"1");
		}
		
		@Override
		public void onException(Exception e) {
			
		}
		@Override
		public void onPostExecuteX(VersionApk result) {
			if(result!=null){
				String version = result.getVersionShort();
				try {
					String versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
					System.out.println("app"+versionName+"-"+version);
					if(version!=null&&!version.equals(versionName)){
						tv_check_result.setText("有最新版本");
						showNoticeDialog(result.getChangelog(), result.getInstallUrl());
					}else{
						tv_check_result.setText("已是最新版本");
					}
				} catch (NameNotFoundException e) {
					
				}
			}else{
				
			}
		}
		
	}
	
	UpdateNoticeDialog noticeDialog;

	private void showNoticeDialog(String content,final String apkUrl) {
		if (noticeDialog == null) {
			noticeDialog = new UpdateNoticeDialog(this);
			noticeDialog.setData(content);
			noticeDialog.setListener(new DialogListener() {

				@Override
				public void onDialogExecute(Object... obj) {
					showDownloadDialog(apkUrl);
				}
			});
		}
		noticeDialog.show();
	}

	private void showDownloadDialog(String apkUrl) {
		DownloadDialog dd = new DownloadDialog(getActivity());
		dd.setData("更新包下载中", apkUrl, "dowish.apk");
		dd.setListener(new DialogListener() {
			
			@Override
			public void onDialogExecute(Object... os) {
				File file = (File) os[0];
				installApk(file);
			}
		});
		dd.show();
		dd.download();
	}

	/**
	 * 安装apk
	 * 
	 * @param url
	 */
	private void installApk(File apkfile) {
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		startActivity(i);
	}
	@Override
	public void onDestroy() {
		Cleaner.cleanTask(task);
		super.onDestroy();
	}

}